<template>
  <div>
    <el-form ref="ruleForm"
             :model="ruleForm"
             :rules="rules"
             class="demo-ruleForm">
      <enterprise-form :rule-form="ruleForm"
                       @input="uploadChange"
                       @areaSelect="areaSelect" />
      <el-form-item prop="mobile">
        <el-input v-model="ruleForm.mobile"
                  type="text"
                  prefix-icon="el-icon-phone"
                  placeholder="注册手机号"
                  @input="changePhone">
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="item-flex">
          <el-input v-model="ruleForm.code"
                    type="text"
                    placeholder="验证码">
          </el-input>
          <el-button v-if="isshowMsgCode"
                     :disabled="sendDisabled"
                     @click="handleSend">发送验证码</el-button>
          <el-button v-if="!isshowMsgCode"
                     disabled>{{ showTime }}秒后重新发送</el-button>
        </div>
        <div class="text">{{ frequency }}</div>
      </el-form-item>
      <el-form-item>
        <div class="item-enroll">
          <el-checkbox v-model="agreementChecked">我已阅读并同意注册协议</el-checkbox>
          <el-link :underline="false"
                   type="primary"
                   @click="agreementVisible = true">用户注册协议</el-link>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button type="primary"
                   style="width: 100%"
                   :loading="loading"
                   @click="handleSubmit">
          注 册
          <!-- <router-link class="router-to"
                       to="/enroll">注 册</router-link> -->
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 注册协议 -->
    <treaty-dialog v-model="agreementVisible"
                   @close="close" />
    <!-- 图形验证码 -->
    <el-dialog top="32vh"
               append-to-body
               width="480px"
               :visible.sync="pictureShow"
               :close-on-click-modal="false">
      <div slot="title">完成拼图验证</div>
      <div v-if="pictureShow"
           class="authen-show">
        <authentication :on-success="success"
                        :on-syntony="picture"
                        width="260"
                        height="120"
                        pl-size="30"
                        deviation="5"
                        :puzzle-img-list="imgLists"
                        class="auth-entication-style"
                        @fatherMethod="pictureShow = false" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TreatyDialog from "./TreatyDialog.vue";
import EnterpriseForm from "./EnterpriseForm.vue";
import { Decrypt } from "@/libs/crypto";
import Authentication from "./Authentication";
import { sendCode, graphicalValidate, register } from "@/api/modules/enroll";
import _ from 'lodash'

export default {
  name: "Enroll",
  components: { TreatyDialog, Authentication, EnterpriseForm },
  props: {
    enroll: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loading: false,
      ruleForm: {},
      rules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
            message: "请輸入正确手机号格式",
            trigger: "blur"
          }
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        tenantName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
          { min: 1, max: 50, message: "不能超50过个字符", trigger: "blur" }
        ],
        source: [
          { required: true, message: "请输入注册来源", trigger: "blur" }
        ],
        socialCreditCode: [
          { required: true, message: "请输入营业执照编码", trigger: "blur" },
          { min: 1, max: 18, message: "不能超18过个字符", trigger: "blur" },
          { pattern: /[\d]/g, message: "只能输入字母和数字" }
        ],
        corporation: [
          { required: true, message: "请输入公司法人", trigger: "blur" },
          { min: 1, max: 10, message: "不能超10过个字符", trigger: "blur" }
        ],
        contactEmail: [
          { required: true, message: "请输入联系邮箱", trigger: "blur" },
          { min: 1, max: 50, message: "不能超50过个字符", trigger: "blur" },
          {
            pattern:
              /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,
            message: "请输入正确的邮箱格式"
          }
        ],
        contactMobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
            message: "请输入正确的手机号码格式"
          }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        alias: [
          { required: true, message: "请输入公司别称", trigger: "blur" },
          { pattern: /^[A-Za-z]+$/g, message: "别名只能输入字母" },
          { min: 5, max: 20, message: "别名只能输入5-20位", trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
          { min: 1, max: 10, message: "不能超10过个字符", trigger: "blur" }
        ]
      },
      showTime: null,
      isshowMsgCode: true,
      agreementChecked: false,
      agreementVisible: false,
      sendDisabled: true,
      pictureShow: false,
      imgLists: [],
      verify: "",
      frequency: "",
      confirmText: []
    };
  },
  watch: {
    enroll: {
      handler (newValue) {
        if (newValue) {
          Object.keys(this.ruleForm).forEach(
            (key) => (this.ruleForm[key] = "")
          );
        }
      }
    }
  },
  methods: {
    handleSubmit: _.debounce(function () {    // 触发事件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.agreementChecked)
            return this.$message.error("同意注册协议才能注册");
          this.confirmEnroll();
        } else {
          return false;
        }
      });
    }, 500),
    handleSend () {
      this.pictureShow = true;
      // this.picture()
    },
    changePhone (val) {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      reg.test(val) ? (this.sendDisabled = false) : (this.sendDisabled = true);
    },
    async changeSendCode (ruleForm) {
      let data = await sendCode(ruleForm);
      const { code, message } = data;
      if (code === 0) {
        this.$message.success(message)
      } else {
        this.$message.error(message);
        this.isshowMsgCode = true;
        // clearInterval(authTimeTimer);
      }
    },
    close (val) {
      this.agreementVisible = val;
    },
    success () {
      this.pictureShow = false;
      this.changeSendCode(this.ruleForm);
      this.sendOutTime();
    },
    picture () {
      graphicalValidate().then((res) => {
        // let { requestId, url, imageName, beginXPoint, beginYPoint, endXPoint, endYPoint } = res.data
        let { iv, imageUrl, imageName, beginX, beginY, endX, endY } = res.data;
        this.ruleForm.requestId = iv;
        const imtUrl = Decrypt(imageUrl, iv, iv) + Decrypt(imageName, iv, iv);
        this.imgLists.push(imtUrl);
        const [o1, o2, o3, o4, o5] = [
          Decrypt(beginX, iv, iv),
          Decrypt(beginY, iv, iv),
          Decrypt(endX, iv, iv),
          Decrypt(endY, iv, iv),
          Decrypt(imageUrl, iv, iv)
        ];
        const verifyList = o5 + iv + o1 + o2 + o3 + o4;
        this.ruleForm.captcha = this.$md5(verifyList);
        this.pictureShow = true;
      });
    },
    sendOutTime () {
      this.isshowMsgCode = false;
      this.showTime = 60;
      const authTimeTimer = setInterval(() => {
        this.showTime--;
        if (this.showTime <= 0) {
          this.isshowMsgCode = true;
          clearInterval(authTimeTimer);
        }
      }, 1000);
    },
    // 地区
    areaSelect (data) {
      this.ruleForm = Object.assign(this.ruleForm, data);
    },
    // 上传营业执照和图片
    uploadChange (data) {
      let area = { ...this.ruleForm.address, address: data?.address };
      this.ruleForm = { ...this.ruleForm, ...data, address: area };
    },
    // 成功提示
    confirmEnroll () {
      const confirmText = [
        "1.物流源将于1个工作日内审核",
        "2.审核结果将已短信通知您",
        "3.审核通过后，您的账号信息将以邮件方式通知",
        "如果您没有收到邮件，可使用注册手机号登录"
      ];
      const newDatas = [];
      const h = this.$createElement;
      for (const i in confirmText) {
        newDatas.push(h("p", null, confirmText[i]));
      }
      this.ruleForm.captcha = this.ruleForm.code;
      register(this.ruleForm).then((res) => {
        const { code, message } = res;
        if (code === 0) {
          this.$confirm("提示", {
            title: "提示",
            message: h("div", null, newDatas),
            showCancelButton: true,
            confirmButtonText: "返回登录",
            type: "success"
          }).then(() => {
            this.ruleForm = {};
            this.$emit("update:enroll", false);
            // this.$router.push({ path: '/login' })
          });
        } else {
          this.$message.error(message);
        }
      });
    }
  }
};
</script>

<style scoped>
.item-flex {
  display: flex;
}
.item-enroll {
  display: flex;
  justify-content: space-between;
}
.router-to {
  text-decoration: none !important;
  color: var(--prev-bg-white);
  font-size: 14px;
}
/* .authen-show {
  width: 100%;
  text-align: center;
  background: #67676770;
  z-index: 999;
  position: fixed;
  height: 100%;
  left: 0;
  right: 0;
  padding-top: 250px;
  top: 0;
} */
.authen-show {
  width: 100%;
  text-align: center;
  z-index: 999;
  height: 100%;
}
.demo-ruleForm >>> .el-input__prefix {
  font-size: 16px;
}
.text {
  color: var(--prev-icon-color-orange);
  font-size: 12px;
  line-height: 20px;
}
</style>
